package org.guegan.util.dircompare.main;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.guegan.util.dircompare.bean.DirBean;
import org.hibernate.Query;

public class DuplFinder extends MainModule {
	private static Log log = LogFactory.getLog(DuplFinder.class);
	
	public DuplFinder() {
	}
	
	public void doExecute() {
		Query query = getSession().getNamedQuery("DirBean.sameName");
		log.debug("Going to run query" + query.getQueryString());
		List<DirBean> res = getSessionUtil().list(query);
		DirBean prev = null;
		for (DirBean dirBean : res) {
			if (!onlySubdirs(dirBean)) {
				if (prev != null && prev.equals(dirBean) && dirBean.getNbFiles() > 30) {
					report("\"" + prev.toString() + "\" and \""
							+ dirBean.toString() + "\" are the same ("
							+ prev.getNbFiles() + ")", log);
				}
				prev = dirBean;
			}
		}
	}

	private boolean onlySubdirs(DirBean dirBean) {
		boolean ret = false;
		Query query = getSession().getNamedQuery("DirBean.nbSubDirs");
		query.setParameter("parent", dirBean);
		Object res = query.uniqueResult();
		ret = ((Long) res).intValue() == dirBean.getNbFiles();
		return ret;
	}
	
	
}
